function roundNumber(rnum, rlength) {
  var newnumber = Math.round(rnum*Math.pow(10,rlength))/Math.pow(10,rlength);
  return parseFloat(newnumber);
}

$(document).ready(function(){
	
	var ajaxRes = 0;
	function loadProjectInfo(id){
		$.ajax({
			url: "/ajax/loadProjectInfo",
			data: "id="+id,
			type: "post",
			beforeSend: function(){
				$("#project_details").html("<div class='loading'></div>");
				ajaxRes++;
			},
			success: function(data){
				if (ajaxRes <= 1){
					$("#project_details").empty();
					var prInfo = $.parseJSON(data);
					
					if (prInfo != null){
						var comPerc = roundNumber(prInfo.complete / (prInfo.complete + prInfo.process + prInfo.query) * 100, 1);
						var div = "<div class='prHeader'>"+prInfo.name+"</div>"+
							"<div class='prAlias'><span class='description'>Алиас:</span> "+prInfo.alias+"</div>"+
							"<div class='complete'>"+
								"<p>Процент готовности: </p>"+
								"<div class='comResult'>"+
									"<div class='comPercent' style='width:"+comPerc+"%'><div class='comShadow'></div></div>"+
									"<div class='comDigit'>"+comPerc+"%</div>"+
								"</div>"+
							"</div>"+
							"<div id='prRec'>"+
								"<p class='prRecCom'>"+prInfo.complete+"</p>"+
							"</div>";
					} else {
						var div = "<div class='gagBig'><p class='gagHeader'>Внезапно!</p><p>Произошла ужастная ошибка!</p><p>Попробуйте перезагрузить страницу!</p></div>";
					}
					
					$("#project_details").append(div);
				}
				ajaxRes--;
			}
		})
	}
	
	$("#project_list td").live("mousedown",function(){
		$(this).addClass("pushed");
	}).live("mouseup",function(){
		$(this).removeClass("pushed");
	}).live("click",function(){
		if ($(this).hasClass("active")){
			$(this).removeClass("active")
			$("#project_list td,inactive").removeClass("inactive");
			$("#project_details").slideUp(200).empty();
		} else {
			$("#project_list td").removeClass("active").addClass("inactive");
			$(this).addClass("active").removeClass("inactive");
			var id = $(this).find(".project_id").val();
			loadProjectInfo(id);
			$("#project_details").slideDown(200);
		}
	})
	
	$(".more_link").mousedown(function(e){ e.stopPropagation(); }).click(function(e){ e.stopPropagation(); })
	
	// DUG initialization
	//Dug.init();
})